/***************************************************************************\
 * Copyright (C) by Keio University
 * Texture.hpp created in 05 2011.
 * Mail : fdesorbi@hvrl.ics.keio.ac.jp
 *
 * Texture.cpp is part of the HVRL Engine Project.
 *
 * The HVRL Engine Project is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * The HVRL Engine Project is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
\***************************************************************************/

#include "hvrl/opengl/Texture.hpp"

#include "hvrl/common/Common.hpp"

Texture2D::Texture2D(void):id(0),size(0,0)
{
}

Texture2D::~Texture2D(void)
{
    if(this->id>0)
    {
        glDeleteTextures(1,&(this->id));
        this->id = 0;
        this->size = glm::uvec2(0,0);
    }
}

bool Texture2D::setData(const glm::uvec2& size, const GLubyte *data, const GLenum& format = GL_RGB)
{
    if(this->id==0)
    {
        glGenTextures(1,&(this->id));
        if(this->id == 0)
        {
           return false;
        }
    }

    glBindTexture(GL_TEXTURE_2D, this->id);
    this->size = size;
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,size[0],size[1],0,format,GL_UNSIGNED_BYTE,data);
    glBindTexture(GL_TEXTURE_2D, 0);
    return true;
}

bool Texture2D::setData(const glm::uvec2& size, const GLfloat *data, const GLenum& format = GL_RGB)
{
    if(this->id==0)
    {
        glGenTextures(1,&(this->id));
        if(this->id == 0)
        {
           return false;
        }
    }

    glBindTexture(GL_TEXTURE_2D, this->id);
    this->size = size;
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,size[0],size[1],0,format,GL_FLOAT,data);
    glBindTexture(GL_TEXTURE_2D, 0);
    return true;
}

void Texture2D::setParameter(const GLenum& pname, const GLint& param)
{
    glBindTexture(GL_TEXTURE_2D, this->id);

    glBindTexture(GL_TEXTURE_2D, 0);
}

void Texture2D::setParameter(const GLenum& pname, const GLfloat& param)
{
    glBindTexture(GL_TEXTURE_2D, this->id);

    glBindTexture(GL_TEXTURE_2D, 0);
}

void Texture2D::getContent(GLubyte *content, const GLenum& format = GL_RGB) const
{
    glBindTexture(GL_TEXTURE_2D, this->id);
    glGetTexImage(GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, content);
    glBindTexture(GL_TEXTURE_2D, 0);
}

void Texture2D::getContent(GLfloat *content, const GLenum& format = GL_RGB) const
{
    glBindTexture(GL_TEXTURE_2D, this->id);
    glGetTexImage(GL_TEXTURE_2D, 0, format, GL_FLOAT, content);
    glBindTexture(GL_TEXTURE_2D, 0);
}

